package org.feng.config;

import io.r2dbc.pool.ConnectionPool;
import io.r2dbc.pool.ConnectionPoolConfiguration;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.r2dbc.core.DatabaseClient;

import java.time.Duration;

import static io.r2dbc.spi.ConnectionFactoryOptions.*;

/**
 * mysql连接池配置：暂时弃用
 *
 * @version V1.0
 * @author: fengjinsong
 * @date: 2022年06月14日 15时24分
 */
@Deprecated
public class MysqlConfig {
    @Bean
    public ConnectionFactory connectionFactory() {
        ConnectionFactoryOptions options = ConnectionFactoryOptions.builder()
                .option(DRIVER, "pool")
                .option(PROTOCOL, "mysql")
                .option(HOST, "127.0.0.1")
                .option(PORT, 3306)
                .option(USER, "root")
                .option(PASSWORD, "123456")
                .option(DATABASE, "test")
                .build();

        return ConnectionFactories.get(options);
    }

    @Bean
    public ConnectionPool connectionPool(@Autowired ConnectionFactory connectionFactory) {
        ConnectionPoolConfiguration configuration = ConnectionPoolConfiguration
                .builder(connectionFactory)
                .maxIdleTime(Duration.ofSeconds(3))
                .maxSize(20)
                .build();

        return new ConnectionPool(configuration);
    }

    @Primary
    @Bean
    public DatabaseClient databaseClient(@Autowired ConnectionFactory connectionFactory) {
        return DatabaseClient.create(connectionFactory);
    }
}
